package cn.kgm.makeGodV2.emotion;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Collectors;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-10-14 15:14
 * @Description: cn.kgm.makeGodV2.emotion.NPCEmotionSystemDouble
 */
public class NPCEmotionSystem {
    // 配置参数
    private static final double MOOD_UPDATE_THRESHOLD = 15.0; // 心境更新阈值
    private static final int MOOD_MEMORY_SIZE = 15; // 记忆的短期状态数量
    private static final double RECENCY_WEIGHT = 0.8; // 近期状态权重
    private static final double MOOD_TRANSITION_FACTOR = 0.2; // 心境变化平滑因子
    private static final double NATURAL_RECOVERY_FACTOR = 0.1; // 自然恢复速度

    // 人格特性
    private final PersonalityTrait personality;
    // 状态列表
    private final Deque<ShortTermState> emotionalMemory;
    // 当前心境
    private EmotionalVector currentMood;
    // 当前短暂状态
    private EmotionalVector currentShortTermState;
    private int moodStabilityCounter; // 心境稳定计数器

    public NPCEmotionSystem(PersonalityTrait personality) {
        this.personality = personality;
        this.currentMood = personality.getBaseEmotionalTendency();
        this.currentShortTermState = personality.getBaseEmotionalTendency();
        this.emotionalMemory = new ConcurrentLinkedDeque<>();
        this.moodStabilityCounter = 0;
    }

    public static void main(String[] args) {
        System.out.println("=== 修仙NPC情感系统 (全double版本) ===\n");

        // 创建不同人格的NPC
        PersonalityTrait optimisticTraits = PersonalityTrait.createOptimistic();
        PersonalityTrait stableTraits = PersonalityTrait.createStable();

        NPCEmotionSystem optimisticNpc = new NPCEmotionSystem(optimisticTraits);
        NPCEmotionSystem stableNpc = new NPCEmotionSystem(stableTraits);

        System.out.println("乐观NPC人格: " + optimisticTraits);
        System.out.println("乐观NPC初始心境: " + optimisticNpc.getCurrentMood());
        System.out.println("稳定NPC人格: " + stableTraits);
        System.out.println("稳定NPC初始心境: " + stableNpc.getCurrentMood());

        // 模拟一系列事件
        System.out.println("\n=== 模拟修仙事件序列 ===\n");

        // 1. 获得灵药
        EmotionalVector joyEmotion = EmotionalVector.createJoy();
        optimisticNpc.processEvent("获得珍稀灵药", joyEmotion);
        stableNpc.processEvent("获得珍稀灵药", joyEmotion);

        // 2. 遭遇强敌
        EmotionalVector fearEmotion = EmotionalVector.createFear();
        optimisticNpc.processEvent("遭遇元婴老怪", fearEmotion);
        stableNpc.processEvent("遭遇元婴老怪", fearEmotion);

        // 3. 战斗失败
        EmotionalVector sadnessEmotion = EmotionalVector.createSadness();
        optimisticNpc.processEvent("战斗重伤败退", sadnessEmotion);
        stableNpc.processEvent("战斗重伤败退", sadnessEmotion);

        // 4. 被同门嘲笑
        EmotionalVector angerEmotion = EmotionalVector.createAnger();
        optimisticNpc.processEvent("被同门嘲笑", angerEmotion);
        stableNpc.processEvent("被同门嘲笑", angerEmotion);

        System.out.println("\n=== 当前状态 ===");
        System.out.println("乐观NPC心境: " + optimisticNpc.getCurrentMood());
        System.out.println("乐观NPC情感: " + optimisticNpc.getCurrentEmotionDescription());
        System.out.println("乐观NPC行为: " + optimisticNpc.getCurrentBehaviorTendency());
        System.out.println("稳定NPC心境: " + stableNpc.getCurrentMood());
        System.out.println("稳定NPC情感: " + stableNpc.getCurrentEmotionDescription());
        System.out.println("稳定NPC行为: " + stableNpc.getCurrentBehaviorTendency());

        // 显示详细分析
        System.out.println("\n=== 详细分析 ===");
        System.out.println("乐观NPC健康度: " + String.format("%.1f", optimisticNpc.getEmotionalHealthScore()) + "/100");
        System.out.println("乐观NPC稳定性: " + optimisticNpc.getMoodStabilityDescription());
        System.out.println("稳定NPC健康度: " + String.format("%.1f", stableNpc.getEmotionalHealthScore()) + "/100");
        System.out.println("稳定NPC稳定性: " + stableNpc.getMoodStabilityDescription());

        // 模拟自然恢复和特殊事件
        System.out.println("\n=== 自然恢复与特殊事件 ===\n");

        // 自然恢复
        for (int i = 0; i < 5; i++) {
            optimisticNpc.naturalMoodRecovery();
            stableNpc.naturalMoodRecovery();
        }

        // 特殊事件：顿悟
        EmotionalVector enlightenmentEmotion = new EmotionalVector(95.0, 45.0, 90.0);
        optimisticNpc.forceSetMood(enlightenmentEmotion);
        stableNpc.forceSetMood(enlightenmentEmotion);

        System.out.println("\n顿悟后状态:");
        System.out.println("乐观NPC: " + optimisticNpc.getCurrentEmotionDescription() + " - " + optimisticNpc.getCurrentBehaviorTendency());
        System.out.println("稳定NPC: " + stableNpc.getCurrentEmotionDescription() + " - " + stableNpc.getCurrentBehaviorTendency());
    }

    /**
     * 处理新的事件，生成短期状态
     */
    public void processEvent(String eventType, EmotionalVector eventEmotion) {
        // 人格特质会影响对事件的反应强度
        EmotionalVector personalityAdjusted = applyPersonalityFilter(eventEmotion);

        // 创建短期状态
        ShortTermState newState = new ShortTermState(personalityAdjusted, eventType);
        emotionalMemory.addFirst(newState);

        // 保持记忆大小
        while (emotionalMemory.size() > MOOD_MEMORY_SIZE) {
            emotionalMemory.removeLast();
        }

        // 更新当前短期状态
        currentShortTermState = personalityAdjusted;

        // 检查是否需要更新心境
        boolean moodChanged = updateMoodIfNeeded();

        if (moodChanged) {
            moodStabilityCounter = 0;
        } else {
            moodStabilityCounter++;
        }

        System.out.println("事件: " + eventType + " -> 短期状态: " + personalityAdjusted +
                " (强度: " + String.format("%.1f", newState.getIntensity()) + ")");
    }

    /**
     * 应用人格过滤器调整情感反应
     */
    private EmotionalVector applyPersonalityFilter(EmotionalVector emotion) {
        double neuroticismFactor = personality.getNeuroticism() / 100.0;
        double extraversionFactor = personality.getExtraversion() / 100.0;
        double agreeablenessFactor = personality.getAgreeableness() / 100.0;

        double adjustedValence = emotion.getValence();
        double adjustedArousal = emotion.getArousal();
        double adjustedDominance = emotion.getDominance();

        // 愉悦度调整：高神经质减弱正面情绪，增强负面情绪
        if (emotion.getValence() > 50.0) {
            // 正面情绪：高神经质的人感受较弱
            adjustedValence = 50.0 + (emotion.getValence() - 50.0) * (1.0 - neuroticismFactor * 0.4);
        } else {
            // 负面情绪：高神经质的人感受更强
            adjustedValence = 50.0 - (50.0 - emotion.getValence()) * (1.0 + neuroticismFactor * 0.5);
        }

        // 唤醒度调整：高神经质增强唤醒度，高外倾性也增强唤醒度
        double arousalMultiplier = 0.7 + neuroticismFactor * 0.5 + extraversionFactor * 0.2;
        adjustedArousal = emotion.getArousal() * arousalMultiplier;

        // 控制度调整：高外倾性增强控制感，高神经质减弱控制感
        double controlMultiplier = 0.6 + extraversionFactor * 0.3 - neuroticismFactor * 0.4;
        adjustedDominance = emotion.getDominance() * controlMultiplier;

        return new EmotionalVector(adjustedValence, adjustedArousal, adjustedDominance);
    }

    /**
     * 检查并更新心境
     */
    private boolean updateMoodIfNeeded() {
        if (emotionalMemory.size() < 5) {
            return false;
        }

        // 计算近期情感状态的加权平均
        EmotionalVector weightedAverage = calculateWeightedEmotionalAverage();

        // 如果与当前心境差异超过阈值，则更新心境
        double distance = currentMood.distanceTo(weightedAverage);
        if (distance > MOOD_UPDATE_THRESHOLD) {
            // 平滑过渡到新心境
            EmotionalVector newMood = currentMood.multiply(1.0 - MOOD_TRANSITION_FACTOR)
                    .add(weightedAverage.multiply(MOOD_TRANSITION_FACTOR));

            System.out.println("*** 心境变化: " + currentMood + " -> " + newMood +
                    " (距离: " + String.format("%.1f", distance) + ") ***");
            currentMood = newMood;
            return true;
        }
        return false;
    }

    /**
     * 计算加权情感平均值（近期状态权重更高）
     */
    private EmotionalVector calculateWeightedEmotionalAverage() {
        List<ShortTermState> recentStates = emotionalMemory.stream()
                .limit(MOOD_MEMORY_SIZE)
                .collect(Collectors.toList());

        double totalWeight = 0.0;
        EmotionalVector sum = new EmotionalVector(0.0, 0.0, 0.0);

        for (int i = 0; i < recentStates.size(); i++) {
            double weight = Math.pow(RECENCY_WEIGHT, i); // 指数衰减权重
            EmotionalVector emotion = recentStates.get(i).getEmotion();

            sum = sum.add(emotion.multiply(weight));
            totalWeight += weight;
        }

        return totalWeight > 0.0 ? sum.divide(totalWeight) : sum;
    }

    /**
     * 自然心境恢复（随时间向人格基线回归）
     */
    public void naturalMoodRecovery() {
        EmotionalVector baseTendency = personality.getBaseEmotionalTendency();

        // 心境越稳定，恢复速度越快
        double stabilityBonus = Math.min(moodStabilityCounter * 0.01, 0.1);
        double recoveryFactor = NATURAL_RECOVERY_FACTOR + stabilityBonus;

        EmotionalVector newMood = currentMood.multiply(1.0 - recoveryFactor)
                .add(baseTendency.multiply(recoveryFactor));

        // 只有变化显著时才更新
        if (currentMood.distanceTo(newMood) > 2.0) {
            currentMood = newMood;
            System.out.println("心境自然恢复: " + currentMood);
        }
    }

    /**
     * 强制设置心境（用于特殊事件）
     */
    public void forceSetMood(EmotionalVector newMood) {
        System.out.println("!!! 强制心境变化: " + currentMood + " -> " + newMood + " !!!");
        currentMood = newMood;
        moodStabilityCounter = 0;

        // 清空短期记忆，因为强制心境变化会覆盖之前的影响
        emotionalMemory.clear();
        emotionalMemory.addFirst(new ShortTermState(newMood, "强制心境变化"));
    }

    /**
     * 获取当前情感描述
     */
    public String getCurrentEmotionDescription() {
        double v = currentMood.getValence();
        double a = currentMood.getArousal();
        double d = currentMood.getDominance();

        // 基于三维坐标判断情感状态
        if (v > 80.0 && a > 70.0) return "狂喜兴奋";
        if (v > 75.0 && a > 60.0) return "兴高采烈";
        if (v > 75.0 && a < 40.0) return "心满意足";
        if (v > 70.0) return "愉悦快乐";

        if (v < 20.0 && a > 80.0 && d > 70.0) return "暴怒狂怒";
        if (v < 25.0 && a > 75.0 && d > 60.0) return "愤怒生气";
        if (v < 25.0 && a > 70.0 && d < 30.0) return "惊恐万分";
        if (v < 25.0 && a < 30.0) return "沮丧抑郁";
        if (v < 30.0) return "悲伤难过";

        if (a > 75.0 && d < 25.0) return "恐慌焦虑";
        if (a > 70.0) return "兴奋激动";
        if (a < 25.0) return "平静安宁";

        if (d > 75.0) return "自信掌控";
        if (d < 25.0) return "无助失控";

        return "平和稳定";
    }

    /**
     * 获取当前行为倾向
     */
    public String getCurrentBehaviorTendency() {
        String emotion = getCurrentEmotionDescription();
        Map<String, String> behaviorMap = new HashMap<>();

        behaviorMap.put("狂喜兴奋", "极度慷慨，乐于助人，充满活力");
        behaviorMap.put("兴高采烈", "乐于助人，慷慨大方，积极社交");
        behaviorMap.put("心满意足", "温和友善，愿意合作，耐心教导");
        behaviorMap.put("愉悦快乐", "积极社交，主动交流，开放接纳");
        behaviorMap.put("暴怒狂怒", "攻击性强，不计后果，易起冲突");
        behaviorMap.put("愤怒生气", "易怒挑衅，抗拒合作，言语尖锐");
        behaviorMap.put("惊恐万分", "逃避危险，寻求保护，难以决策");
        behaviorMap.put("沮丧抑郁", "回避社交，消极怠惰，放弃努力");
        behaviorMap.put("悲伤难过", "寻求安慰，需要独处，效率低下");
        behaviorMap.put("恐慌焦虑", "过度警惕，犹豫不决，依赖他人");
        behaviorMap.put("兴奋激动", "精力充沛，主动探索，快速决策");
        behaviorMap.put("平静安宁", "理性决策，稳定行动，可靠执行");
        behaviorMap.put("自信掌控", "领导姿态，果断决策，承担责任");
        behaviorMap.put("无助失控", "依赖他人，难以决断，寻求指导");
        behaviorMap.put("平和稳定", "行为正常，反应可期，理性合作");

        return behaviorMap.getOrDefault(emotion, "行为正常，反应可期");
    }

    /**
     * 获取情感健康度评分 (0.0-100.0)
     */
    public double getEmotionalHealthScore() {
        // 基于心境稳定性、愉悦度水平等计算
        double stabilityScore = 100.0 - calculateEmotionalVolatility() * 1.5;
        double positivityScore = currentMood.getValence();
        double balanceScore = 100.0 - Math.abs(currentMood.getArousal() - 50.0) * 0.8;

        return (stabilityScore + positivityScore + balanceScore) / 3.0;
    }

    /**
     * 计算情感波动性
     */
    private double calculateEmotionalVolatility() {
        if (emotionalMemory.size() < 2) return 0.0;

        double totalChange = 0.0;
        ShortTermState previous = null;

        for (ShortTermState current : emotionalMemory) {
            if (previous != null) {
                totalChange += previous.getEmotion().distanceTo(current.getEmotion());
            }
            previous = current;
        }

        return totalChange / (emotionalMemory.size() - 1);
    }

    /**
     * 获取心境稳定性描述
     */
    public String getMoodStabilityDescription() {
        double volatility = calculateEmotionalVolatility();

        if (volatility < 10.0) return "极其稳定";
        if (volatility < 20.0) return "较为稳定";
        if (volatility < 30.0) return "中等稳定";
        if (volatility < 40.0) return "较为波动";
        return "极其波动";
    }

    // Getters
    public EmotionalVector getCurrentMood() {
        return currentMood;
    }

    public EmotionalVector getCurrentShortTermState() {
        return currentShortTermState;
    }

    public PersonalityTrait getPersonality() {
        return personality;
    }

    public List<ShortTermState> getRecentEmotions() {
        return new ArrayList<>(emotionalMemory);
    }

    public int getMoodStabilityCounter() {
        return moodStabilityCounter;
    }
}
